package com.xx.eshop.service.impl;

import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.xx.eshop.dao.CategoryDao;
import com.xx.eshop.entity.Category;
import com.xx.eshop.service.CategoryService;

@Service
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
public class CategoryServiceImpl implements CategoryService {

	@Autowired
	private CategoryDao categoryDao;

	public Category findById(int id){
		return categoryDao.findById(id);
	}
	
	@Override
	@Transactional
	public void save(Category category) {
		categoryDao.save(category);
	}

	@Override
	@Transactional
	public void delete(int id) {
		categoryDao.delete(id);
	}

	@Override
	public Category findOne(int id) {
		return categoryDao.findById(id);
	}

	@Override
	public List<Category> findAll() {
		return categoryDao.findAll();
	}

	@Override
	public List<Category> findByPid(int pid) {
		return categoryDao.findByPid(pid);
	}

	@Override
	public int findNextId(int pid) {
		Integer max = categoryDao.findNextId(pid);
		if (max == null) { // 没有子元素
			int level = getLevel(pid);
			if (level == 0) {
				return pid + 1000000;
			} else if (level == 1) {
				return pid + 10000;
			} else {
				return pid + 100;
			}
		} else {
			int level = getLevel(max);
			if (level == 3) {
				return max + 100;
			} else if (level == 2) {
				return max + 10000;
			} else {
				return max + 1000000;
			}
		}
	}

	private int getLevel(int id) {
		if (id / 100 % 100 > 0) { // 3级
			return 3;
		} else if (id / 10000 % 100 > 0) { // 二级
			return 2;
		} else if (id / 1000000 % 100 > 0) { // 一级
			return 1;
		} else {
			return 0;
		}
	}

	@Override
	@Transactional
	public void update(Category category, Map<String, Integer> rowsmap) {
		categoryDao.update(category);
		// 找到它平级的所有类别
		List<Category> siblings = categoryDao.findByPid(category.getParent_id());
		// {"1020000":1010000, "1010000":1020000, ...} ==> Map<String, Integer>
		for (Category c : siblings) {
			// c.getId() 1020000
			int sort = rowsmap.get(c.getId() + ""); // 获取新的sort
			c.setSort(sort);
			categoryDao.update(c);
		}
	}

}
